package lightrain.code.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;


public class DigestUtils extends org.apache.commons.codec.digest.DigestUtils{

	private static final String AES_NAME = "AES";
	
	private static final String AES_KEY = "MQyVUmEfSdNMFdYn";
	
	
	/**
	 * 加密
	 * 
	 * @author YUE
	 * @date 2013-4-12 下午4:50:16
	 * @param value
	 * @return
	 */
	public static String AESDencrypt(String value){
		return AESDecrypt(AES_KEY, value);
	}

	/**
	 * 解密
	 * 
	 * @author YUE
	 * @date 2013-4-12 下午4:51:37
	 * @param value
	 * @return
	 */
	public static String AESEncrypt(String value){
		return AESEncrypt(AES_KEY, value);
	}
	
	/**
	 * 加密
	 * @param key
	 * @param value
	 * @return
	 */
	public static String AESEncrypt(String key,String value){
		try{
			SecretKey secretKey = new SecretKeySpec(key.getBytes(),AES_NAME);
			SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), AES_NAME);
			Cipher cipher = Cipher.getInstance(AES_NAME);
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);
			return Hex.encodeHexString(cipher.doFinal(value.getBytes()));
		}
		catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/***
	 *解密
	 * @param key
	 * @param value
	 * @return
	 */
	public static String AESDecrypt(String key,String value){
		try{
			SecretKey secretKey = new SecretKeySpec(key.getBytes(),AES_NAME);
			SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(),AES_NAME);
			Cipher cipher = Cipher.getInstance(AES_NAME);
			cipher.init(Cipher.DECRYPT_MODE, keySpec);
			byte[] bytes = cipher.doFinal(Hex.decodeHex(value.toCharArray()));
			return new String(bytes);
		}catch (Exception e){
			//解密失败
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * @auther Y.hj
	 * @param password
	 * @return
	 */
	public static String pwdEncrypt(String password){
		return md5Hex(password+AES_KEY);
	}
	
}
